import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;


//批量插入
public class Batch_Insertion {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/mysqlbase?serverTimezone=GMT&characterEncoding=utf8";
        String user = "root";
        String password = "1234";
        String sql = "INSERT INTO teacher (id, name, course, birthday) VALUES (?, ? ,? ,? )";
        try (Connection connection = DriverManager.getConnection(url, user, password)){
            connection.setAutoCommit(false);
            try (PreparedStatement ps = connection.prepareStatement(sql)){
                for(int i=1;i<=500;i++){
                    ps.setInt(1, i);
                    ps.setString(2, "teacher"+i);
                    ps.setString(3, "course"+i);
                    ps.setString(4, "2000-01-01");
                    ps.addBatch();
                    if(i%100==0){
                        ps.executeBatch();
                        ps.clearBatch();
                    }
                }
                ps.executeBatch();
                connection.commit();
                System.out.println("OK!");
            }catch (SQLException e){
                connection.rollback();
                e.printStackTrace();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}
